package com.showsu.editor.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.showsu.editor.dao.TblSmsLogMapper;
import com.showsu.editor.entity.doo.SmsLog;
import com.showsu.editor.entity.po.TblSmsLog;
import com.showsu.editor.enums.RowFlagEnum;
import com.showsu.editor.service.ISmsLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: William
 * @Description:
 * @Date: Created in 7:59 下午 2023/3/20
 * @Modified By:
 */
@Service
@Slf4j
public class SmsLogServiceImpl extends ServiceImpl<TblSmsLogMapper, TblSmsLog> implements ISmsLogService {

    @Autowired
    private TblSmsLogMapper smsLogMapper;

    @Override
    public int saveRecord(String mobile, String code, String ip) {
        TblSmsLog smsLog = new TblSmsLog();
        smsLog.setMobile(mobile);
        smsLog.setSmsCode(code);
        smsLog.setClientIp(ip);
        return smsLogMapper.insert(smsLog);
    }

    @Override
    public int checkedById(Long id, Long userId) {
        TblSmsLog smsLog = new TblSmsLog();
        smsLog.setId(id);
        smsLog.setUserId(userId);
        smsLog.setChecked(1);
        return smsLogMapper.updateById(smsLog);
    }

    @Override
    public SmsLog queryByCode(String code) {
        if (StringUtils.isBlank(code)) {
            return null;
        }
        TblSmsLog tblSmsLog = smsLogMapper.selectOne(new QueryWrapper<TblSmsLog>().lambda()
                .eq(TblSmsLog::getSmsCode, code)
                .eq(TblSmsLog::getFlag, RowFlagEnum.UnDelete.getCode()));
        return tblSmsLog == null ? null : BeanUtil.copyProperties(tblSmsLog, SmsLog.class);
    }

    @Override
    public SmsLog queryLastUnckeckedOneByMobile(String mobile) {
        TblSmsLog tblSmsLog = smsLogMapper.selectOne(new QueryWrapper<TblSmsLog>().lambda()
                .eq(TblSmsLog::getMobile, mobile)
                .eq(TblSmsLog::getFlag, RowFlagEnum.UnDelete.getCode())
                .eq(TblSmsLog::getChecked, 0)
                .orderByDesc(TblSmsLog::getId).last("limit 1"));
        return tblSmsLog == null ? null : BeanUtil.copyProperties(tblSmsLog, SmsLog.class);
    }
}
